package com.xijia.wuyouwallet.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.squareup.picasso.Picasso;
import com.xijia.wuyouwallet.MyApp;
import com.xijia.wuyouwallet.R;
import com.xijia.wuyouwallet.api.MyCallBack;
import com.xijia.wuyouwallet.base.BaseActivity;
import com.xijia.wuyouwallet.bean.AmountData;
import com.xijia.wuyouwallet.bean.BankListData;
import com.xijia.wuyouwallet.bean.PayData;
import com.xijia.wuyouwallet.bean.RateData;
import com.xijia.wuyouwallet.utils.Constants;
import com.xijia.wuyouwallet.utils.StringUtils;
import com.xijia.wuyouwallet.utils.UrlConfig;
import com.xijia.wuyouwallet.utils.XUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/25 0025.
 */

public class ReceiptMoneyActivity extends BaseActivity implements View.OnClickListener{

    private ImageView receipt_money_back;
    private TextView receipt_money_bills;
    private TextView receipt_money_tv;
    //private GridView receipt_money_gv;

    private LinearLayout receipt_money_sure;

    private TextView receipt_money_1,receipt_money_2,receipt_money_3,receipt_money_4,receipt_money_5,receipt_money_6,
            receipt_money_7,receipt_money_8,receipt_money_9,receipt_money_0,receipt_money_point,receipt_money_d0,receipt_money_delet;

    private List<String> numList = new ArrayList<String>();
    private int numIndex=0;
    //新增加
    private LinearLayout receipt_money_payBank_ll,receipt_money_receiveBank_ll;

    private LinearLayout receipt_money_payBank_bll,receipt_money_receiveBank_bll;
    private ImageView receipt_money_payBank_img,receipt_money_receiveBank_img;
    private TextView receipt_money_payBank_name,receipt_money_payBank_num,receipt_money_receiveBank_name,receipt_money_receiveBank_num;

    private TextView receipt_money_quotaTv,receipt_money_nowRateTv;

    private String payCardId = null;
    private String receiveCardId = null;

    //红包
    private Dialog redpacketDialog;
    private ImageView awardPacket_close_img;
    private TextView awardPacket_money_tv;

    //支付类型
    private String ct_id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receipt_money);
        initView();
        //setUpPayKeyAdapter();
    }

    private void initRedpacketDialog(){
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_award_redpacket,null);
        redpacketDialog = new Dialog(this, R.style.redPacketDialogStyle);
        awardPacket_close_img = (ImageView) view.findViewById(R.id.awardPacket_close_img);
        awardPacket_close_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                redpacketDialog.dismiss();
            }
        });
        awardPacket_money_tv = (TextView) view.findViewById(R.id.awardPacket_money_tv);
        redpacketDialog.setContentView(view);
        redpacketDialog.setCanceledOnTouchOutside(false);
        //redpacketDialog.show();
    }
    /**
     * 获取首刷红包金额
     */
    private void requestPacketData(){
        Map<String,Object> map = new HashMap<>();
        map.put("token",MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        XUtil.Post(UrlConfig.FIRST_SWEIP_REDPACKET,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //MyLogger.wLog().e("获取实名认证奖励红包result="+result);
                AmountData data = JSONObject.parseObject(result,AmountData.class);
                if (data.getCode()==200){
                    initRedpacketDialog();
                    awardPacket_money_tv.setText(data.getData().getAmount());
                    redpacketDialog.show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                //MyLogger.wLog().e("获取首刷红包onError="+ex.toString());
            }
        });
    }
    private void initView(){
        receipt_money_back = (ImageView) findViewById(R.id.receipt_money_back);
        receipt_money_back.setOnClickListener(this);
        receipt_money_bills = (TextView) findViewById(R.id.receipt_money_bills);
        receipt_money_bills.setOnClickListener(this);
        receipt_money_tv = (TextView) findViewById(R.id.receipt_money_tv);
        //receipt_money_gv = (GridView) findViewById(R.id.receipt_money_gv);

        receipt_money_sure = (LinearLayout) findViewById(R.id.receipt_money_sure);
        receipt_money_sure.setOnClickListener(this);

        receipt_money_1 = (TextView) findViewById(R.id.receipt_money_1);
        receipt_money_1.setOnClickListener(this);

        receipt_money_2 = (TextView) findViewById(R.id.receipt_money_2);
        receipt_money_2.setOnClickListener(this);

        receipt_money_3 = (TextView) findViewById(R.id.receipt_money_3);
        receipt_money_3.setOnClickListener(this);

        receipt_money_4 = (TextView) findViewById(R.id.receipt_money_4);
        receipt_money_4.setOnClickListener(this);

        receipt_money_5 = (TextView) findViewById(R.id.receipt_money_5);
        receipt_money_5.setOnClickListener(this);

        receipt_money_6 = (TextView) findViewById(R.id.receipt_money_6);
        receipt_money_6.setOnClickListener(this);

        receipt_money_7 = (TextView) findViewById(R.id.receipt_money_7);
        receipt_money_7.setOnClickListener(this);

        receipt_money_8 = (TextView) findViewById(R.id.receipt_money_8);
        receipt_money_8.setOnClickListener(this);

        receipt_money_9 = (TextView) findViewById(R.id.receipt_money_9);
        receipt_money_9.setOnClickListener(this);

        receipt_money_0 = (TextView) findViewById(R.id.receipt_money_0);
        receipt_money_0.setOnClickListener(this);

        receipt_money_point = (TextView) findViewById(R.id.receipt_money_point);
        receipt_money_point.setOnClickListener(this);

        receipt_money_d0 = (TextView) findViewById(R.id.receipt_money_d0);
        receipt_money_d0.setOnClickListener(this);

        receipt_money_delet = (TextView) findViewById(R.id.receipt_money_delet);
        receipt_money_delet.setOnClickListener(this);


        //新改
        receipt_money_payBank_ll = (LinearLayout) findViewById(R.id.receipt_money_payBank_ll);
        receipt_money_payBank_ll.setOnClickListener(this);
        receipt_money_receiveBank_ll = (LinearLayout) findViewById(R.id.receipt_money_receiveBank_ll);
        receipt_money_receiveBank_ll.setOnClickListener(this);

        receipt_money_payBank_bll = (LinearLayout) findViewById(R.id.receipt_money_payBank_bll);
        receipt_money_payBank_bll.setOnClickListener(this);
        receipt_money_receiveBank_bll = (LinearLayout) findViewById(R.id.receipt_money_receiveBank_bll);
        receipt_money_receiveBank_bll.setOnClickListener(this);

        receipt_money_payBank_img = (ImageView) findViewById(R.id.receipt_money_payBank_img);
        receipt_money_receiveBank_img = (ImageView) findViewById(R.id.receipt_money_receiveBank_img);

        receipt_money_payBank_name = (TextView) findViewById(R.id.receipt_money_payBank_name);
        receipt_money_payBank_num = (TextView) findViewById(R.id.receipt_money_payBank_num);
        receipt_money_receiveBank_name = (TextView) findViewById(R.id.receipt_money_receiveBank_name);
        receipt_money_receiveBank_num = (TextView) findViewById(R.id.receipt_money_receiveBank_num);

        receipt_money_quotaTv = (TextView) findViewById(R.id.receipt_money_quotaTv);
        receipt_money_quotaTv.setOnClickListener(this);
        receipt_money_nowRateTv = (TextView) findViewById(R.id.receipt_money_nowRateTv);
        receipt_money_nowRateTv.setOnClickListener(this);

        ct_id = getIntent().getStringExtra("ct_id");
        requestRate();
        requestBankData();
    }


    @Override
    protected void onResume() {
        super.onResume();
        requestPacketData();
        if (MyApp.isRateResh){
            MyApp.isRateResh = false;
            requestRate();
        }
    }

    /**
     * 计算数据
     */
    private void computeNum(String keytype,String textValue){
        String money = receipt_money_tv.getText().toString();
        //Log.e("info","进入计算");
        if (keytype.equals("num")){//数字键

            try {
                String orgValue = numList.get(numIndex);
                if (money.equals("0")){
                    receipt_money_tv.setText(textValue);
                }else {
                    //小数点最多只能后两位
                    if(orgValue.equals("0.00")){
                        orgValue=textValue;
                        numList.set(numIndex, textValue);
                        receipt_money_tv.setText(textValue);
                        return;
                    }
                    if(orgValue.lastIndexOf(".")!=-1 && orgValue.lastIndexOf(".")<orgValue.length()-2){
                        Toast.makeText(getApplicationContext(),"只能输入小数点后两位",Toast.LENGTH_SHORT).show();
                    }else {
                        if(money.length()>=18){
                            Toast.makeText(getApplicationContext(),"一次输入算式无法超过18个字符",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        int numLen = orgValue.length();
                        if(orgValue.lastIndexOf(".")!=-1){
                            numLen = orgValue.lastIndexOf(".")+1;
                        }
                        if(numLen==9){
                            Toast.makeText(getApplicationContext(),"收款金额不能超过9位数",Toast.LENGTH_SHORT).show();
                        }else{
                            numList.set(numIndex, orgValue+textValue);
                            receipt_money_tv.setText(money+textValue);
                        }
                    }
                }

            }catch (Exception e){
                numIndex=0;
                numList=new ArrayList<String>();
                numList.add(textValue);
                receipt_money_tv.setText(textValue);
            }

        }
        if(keytype.equals("back")){
            //退格
            try{
                if(money.lastIndexOf("+") == money.length()-1){
                    //最后为加则减少一位
                    numList.set(numIndex,"");
                    numIndex--;
                    receipt_money_tv.setText(money.substring(0,money.length()-1));
                }else{
                    String orgValue = numList.get(numIndex);
                    if(!orgValue.equals("")){
                        numList.set(numIndex, orgValue.substring(0,orgValue.length()-1));
                    }
                    if(money.equals("0")||money.length()==1){
                        receipt_money_tv.setText("0.00");
                        numList.set(numIndex,"0.00");
                    }else{
                        receipt_money_tv.setText(money.substring(0,money.length()-1));
                    }
                }
            }catch(Exception e){
                numIndex=0;
                numList=new ArrayList<String>();
                numList.add("0");
                receipt_money_tv.setText("");
            }
        }
        if(keytype.equals("point")){
            //小数点
            try{
                String orgValue = numList.get(numIndex);
                if(orgValue.lastIndexOf(".")!=-1){
                    Toast.makeText(getApplicationContext(),"已存在小数点",Toast.LENGTH_SHORT).show();
                }else{
                    if(money.lastIndexOf("+") == money.length()-1){
                        //最后为加则补0
                        numList.set(numIndex, orgValue+"0"+textValue);
                        receipt_money_tv.setText(money+"0"+textValue);
                    }else{
                        numList.set(numIndex, orgValue+textValue);
                        receipt_money_tv.setText(money+textValue);
                    }
                }
            }catch(Exception e){
                numIndex=0;
                numList=new ArrayList<String>();
                numList.add("0.");
                receipt_money_tv.setText("0.");
            }
        }
        if (keytype.equals("pay")){
            //等于
            try{
                double sum = 0.0;
                for(String value :numList){
                    if(!value.equals("")){
                        sum+= Double.parseDouble(value)+0.00d;
                    }
                }

                String sumStr=new DecimalFormat("##.##").format(sum);
                if(!sumStr.contains(".")){
                    sumStr+=".00";
                }
                if(sumStr.substring(sumStr.lastIndexOf(".")+1).length()<2){
                    sumStr+="0";
                }

                numIndex=0;
                numList=new ArrayList<String>();
                numList.add(sumStr);
                receipt_money_tv.setText(sumStr);
            }catch(Exception e){
                numIndex=0;
                numList=new ArrayList<String>();
                numList.add("0");
                receipt_money_tv.setText("");
            }
        }
    }

    @Override
    public void onClick(View view) {
        Bundle bundle = null;
        switch (view.getId()){
            case R.id.receipt_money_back:
                finish();
                break;
            case R.id.receipt_money_bills://账单
                jumpToPage(TradeBillActivity.class);
                break;
            case R.id.receipt_money_sure://确认收款
                //showToast("确认收款");
                if (payCardId==null){
                    showToast("请选择支付银行卡");
                    return;
                }
                if (receiveCardId==null){
                    showToast("请选择收款银行卡");
                    return;
                }
                if (payCardId.equals(receiveCardId)){
                    showToast("支付与收款卡号不能相同");
                    return;
                }
                computeNum("pay","");
                if (receipt_money_tv.getText().toString().length() < 1||receipt_money_tv.getText().toString().equals("0.00") || receipt_money_tv.getText().toString().equals("0")) {
                    showToast("请输入金额");
                    return;
                }else {
                    String money =  receipt_money_tv.getText().toString();
                    Double dMoney = Double.parseDouble(money);
                    if (dMoney<1){
                        showToast("交易金额不能小于1.00元");
                        return;
                    }
                    if (ct_id.equals("5")){
                        //普通支付
                        shortPayA(money);
                    }else if (ct_id.equals("6")){
                        shortPayB(money);
                    }
                }
                break;
            case R.id.receipt_money_1:
                computeNum("num","1");
                break;
            case R.id.receipt_money_2:
                computeNum("num","2");
                break;
            case R.id.receipt_money_3:
                computeNum("num","3");
                break;
            case R.id.receipt_money_4:
                computeNum("num","4");
                break;
            case R.id.receipt_money_5:
                computeNum("num","5");
                break;
            case R.id.receipt_money_6:
                computeNum("num","6");
                break;
            case R.id.receipt_money_7:
                computeNum("num","7");
                break;
            case R.id.receipt_money_8:
                computeNum("num","8");
                break;
            case R.id.receipt_money_9:
                computeNum("num","9");
                break;
            case R.id.receipt_money_0:
                computeNum("num","0");
                break;
            case R.id.receipt_money_point:
                computeNum("point",".");
                break;
            case R.id.receipt_money_d0:
                computeNum("num","0");
                computeNum("num","0");
                break;
            case R.id.receipt_money_delet:
                computeNum("back","←");
                break;
            case R.id.receipt_money_payBank_ll://选择支付信用卡
                MyApp.isRefund = false;
                bundle = new Bundle();
                bundle.putString("cardType","0");
                jumpToPage(ChoiceBankActivity.class,bundle,true, Constants.REQUEST_DATA,false);
                break;
            case R.id.receipt_money_receiveBank_ll://选择收款银行
                MyApp.isRefund = false;
                bundle = new Bundle();
                bundle.putString("cardType","1");
                jumpToPage(ChoiceBankActivity.class,bundle,true, Constants.REQUEST_DATA_THREE,false);
                break;
            case R.id.receipt_money_payBank_bll://选择支付信用卡
                MyApp.isRefund = false;
                bundle = new Bundle();
                bundle.putString("cardType","0");
                jumpToPage(ChoiceBankActivity.class,bundle,true, Constants.REQUEST_DATA,false);
                break;
            case R.id.receipt_money_receiveBank_bll://选择收款银行
                MyApp.isRefund = false;
                bundle = new Bundle();
                bundle.putString("cardType","1");
                jumpToPage(ChoiceBankActivity.class,bundle,true, Constants.REQUEST_DATA_THREE,false);
                break;
            case R.id.receipt_money_nowRateTv://当前费率
                jumpToPage(UpgradeNewActivity.class);
                break;
            case R.id.receipt_money_quotaTv://限额说明
                bundle = new Bundle();
                bundle.putString("url",UrlConfig.GET_QUOTA_URL+"/id/"+ct_id);
                jumpToPage(CommonWvActivity.class,bundle);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==Constants.REQUEST_DATA&&resultCode==Constants.RESULT_DATA){
            String img = data.getStringExtra("img");
            String name = data.getStringExtra("name");
            String num = data.getStringExtra("num");
            payCardId = data.getStringExtra("cardId");
            String cardType = data.getStringExtra("cardType");
            Picasso.with(this).load(img).fit().into(receipt_money_payBank_img);
            receipt_money_payBank_name.setText(name);
            if (cardType.equals("0")){
                receipt_money_payBank_num.setText("尾号"+ StringUtils.hintBankFourNum(num)+"信用卡");
            }else if (cardType.equals("1")){
                receipt_money_payBank_num.setText("尾号"+ StringUtils.hintBankFourNum(num)+"储蓄卡");
            }
            receipt_money_payBank_ll.setVisibility(View.GONE);
            receipt_money_payBank_bll.setVisibility(View.VISIBLE);
        }else if (requestCode==Constants.REQUEST_DATA_THREE&&resultCode==Constants.RESULT_DATA){
            String img = data.getStringExtra("img");
            String name = data.getStringExtra("name");
            String num = data.getStringExtra("num");
            receiveCardId = data.getStringExtra("cardId");
            String cardType = data.getStringExtra("cardType");
            Picasso.with(this).load(img).fit().into(receipt_money_receiveBank_img);
            receipt_money_receiveBank_name.setText(name);
            if (cardType.equals("0")){
                receipt_money_receiveBank_num.setText("尾号"+ StringUtils.hintBankFourNum(num)+"信用卡");
            }else if (cardType.equals("1")){
                receipt_money_receiveBank_num.setText("尾号"+ StringUtils.hintBankFourNum(num)+"储蓄卡");
            }
            receipt_money_receiveBank_ll.setVisibility(View.GONE);
            receipt_money_receiveBank_bll.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 获取默认银行卡
     */
    private void requestBankData(){
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("type","1");
        showProgressDialog(true);
        XUtil.Post(UrlConfig.GET_BANKCARD_LIST,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                dismissProgressDialog();
                //MyLogger.wLog().e("获取银行卡列表result="+result);
                BankListData data = JSONObject.parseObject(result,BankListData.class);
                if (data.getCode()==200){
                    String img = data.getData().getList().get(0).getBank_logo();
                    String name = data.getData().getList().get(0).getCard_bank();
                    String num = data.getData().getList().get(0).getCard_number();
                    receiveCardId = data.getData().getList().get(0).getCard_id();
                    //String cardType = data.getStringExtra("cardType");
                    Picasso.with(ReceiptMoneyActivity.this).load(img).fit().into(receipt_money_receiveBank_img);
                    receipt_money_receiveBank_name.setText(name);
                    receipt_money_receiveBank_num.setText("尾号"+ StringUtils.hintBankFourNum(num)+"储蓄卡");
                    receipt_money_receiveBank_ll.setVisibility(View.GONE);
                    receipt_money_receiveBank_bll.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                dismissProgressDialog();
                //MyLogger.wLog().e("获取银行卡列表onError="+ex.toString());
            }
        });
    }
    /**
     * 获取费率
     */
    private void requestRate(){
        Map<String,Object> map = new HashMap<>();
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("ct_id",ct_id);
        XUtil.Post(UrlConfig.GET_USER_RATE_URL,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //MyLogger.wLog().e("获取当前费率result="+result);
                RateData data = JSONObject.parseObject(result,RateData.class);
                if (data.getCode()==200){
                    receipt_money_nowRateTv.setText("当前费率"+data.getData().getList().getChannel_rate()+"  点击降低费率");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                //MyLogger.wLog().e("获取当前费率onError="+ex.toString());
            }
        });
    }
    /**
     * 支付B
     */
    private void shortPayB(final String money){
        Map<String,Object> map = new HashMap<>();
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("token",MyApp.userData.getData().getToken());
        showProgressDialog(true);
        XUtil.Post(UrlConfig.REPORT_PAY_URL,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                dismissProgressDialog();
                //MyLogger.wLog().e("快捷支付Bresult="+result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getInteger("code")==200){
                    String payUrl = UrlConfig.EASYPASS_PAY_URL +"/user/"+
                            MyApp.userData.getData().getUser_id()+"/card_id/"+payCardId+"/payamt/"+money;
                    //Log.e("info","shortPayB payUrl="+payUrl);
                    Bundle bundle = new Bundle();
                    bundle.putString("url",payUrl);
                    jumpToPage(PayWvActivity.class,bundle,true);
                }else {
                    showToast(jsonObject.getString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                dismissProgressDialog();
                showToast("支付失败");
                //MyLogger.wLog().e("快捷支付BonError="+ex.toString());
            }
        });
    }

    /**
     * 支付A
     *
     * @param money
     */
    private void shortPayA(String money){
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("price",money);
        map.put("payCardId",payCardId);
        map.put("recieveCardId",receiveCardId);
        showProgressDialog(true);
        XUtil.Post(UrlConfig.SHORT_PAY_URL,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                dismissProgressDialog();
                //MyLogger.wLog().e("快捷支付result="+result);
                PayData data = JSONObject.parseObject(result,PayData.class);
                if (data.getCode().equals("200")){
                    Bundle bundle = new Bundle();
                    bundle.putString("url",data.getData().getUrl());
                    jumpToPage(PayWvActivity.class,bundle,true);
                }else {
                    showToast(data.getMsg());
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                dismissProgressDialog();
                //MyLogger.wLog().e("快捷支付onError="+ex.toString());
                showToast("支付失败");
            }
        });
    }

}
